//index.js
import {convertToChinaNum,getmatchshortname} from '../../utils/utils';
const app = getApp()




Page({
  data: {
    staticUrl: app.globalData.staticUrl,
    baseimgaeUrl: app.globalData.imageBaseUrl,
    rankingimage:app.globalData.imagebaseUrlTest,
    logoUrl: '',
    avatarUrl: app.globalData.imageunlogurl,
    indexpageUrl: undefined,
    news_url: "",
    news_items: undefined,
    selectarea:'全国',
    matchinprepare:"",
     titlecontent:"君品习酒中国精英公开赛",
     mytour:'',
    channels_items:[
      /*{channalid:'1',channelname:'2020沃尔沃中国青少年大师赛一轮#青少年高尔夫赛事',
    finderUserName:'sphY9HOTLiCELsX',
    thurmb:'https://finder.video.qq.com/251/20350/stodownload?encfilekey=RBfjicXSHKCOONJnTbRmmlD8cOQPXE48ibS2R3DX7mrjX4ibGRc0yNo957nCT8hts44SEhk3SBCVnbe89xzwn5ibCuOafcWqow80AmdJLbM4lLmMZlWRQiaJaEV14P21icRKDXITzxrst5s0rZJtNP71HWVSLxtUW7EicdW&token=x5Y29zUxcibCCvu3oBXsbwwHJAicibRIia0qibJ26EibC6dHRwN9paUAq82eXzAJ4Lldp8BKkE1ZEuQhY&idx=1&bizid=1023&dotrans=0&hy=SZ&m=634a36cae17239989b9021558eb41140',
    feedId:'export/UzFfAgtgekIEAQAAAAAAx4svuPCuAgAAAAstQy6ubaLX4KHWvLEZgBPE_KFQEEt-AuL4zNPgMJqzRAbzYlNetKRKU8mMnzjk',
    },{channalid:'1',channelname:'2020沃尔沃中国青少年大师赛一轮#青少年高尔夫赛事',
    finderUserName:'sphY9HOTLiCELsX',
    thurmb:'https://finder.video.qq.com/251/20350/stodownload?encfilekey=RBfjicXSHKCOONJnTbRmmlD8cOQPXE48ibS2R3DX7mrjX4ibGRc0yNo957nCT8hts44SEhk3SBCVnbe89xzwn5ibCuOafcWqow80AmdJLbM4lLmMZlWRQiaJaEV14P21icRKDXITzxrst5s0rZJtNP71HWVSLxtUW7EicdW&token=x5Y29zUxcibCCvu3oBXsbwwHJAicibRIia0qibJ26EibC6dHRwN9paUAq82eXzAJ4Lldp8BKkE1ZEuQhY&idx=1&bizid=1023&dotrans=0&hy=SZ&m=634a36cae17239989b9021558eb41140',
    feedId:'export/UzFfAgtgekIEAQAAAAAAx4svuPCuAgAAAAstQy6ubaLX4KHWvLEZgBPE_KFQEEt-AuL4zNPgMJqzRAbzYlNetKRKU8mMnzjk',
    }*/
  ],
    events_items:[
      /*{
      thurmbs:[
        {thrumtype:"video",
        src:"https://apd-ac3d937c78deefa90481d5c93d4d7b89.v.smtcdns.com/om.tc.qq.com/ADeO_cF9qxjTeMtEIyUsijL-maVpiFs5jbmYzd4lmvW8/uwMROfz2r5zEIaQXGdGnC2dfDmafRkP9ujxgqKjuATzMrE-2/p051938aasg.mp4?sdtfrom=v1010&guid=d915c6d6e8581c763640080e26c56e9d&vkey=D974D57CD88F1F90C3355F7083B982F15F4417E0B013FB2348DE16AA74885FC334AB350775B6C94D4BAAA1F6D18513A20A61D84B94DDED1114CF73BC3FBA76B71B45E39B03BFA04536378831705039298D10907665C3ABE59627C41CF3FDD35DB111E18EA6C4D0D662B8B46FA47455EB9B505D80B32EBCED85E983457D4A88277630CA57DEA825CC"},
        {
          thrumtype:"image",
          src:"https://img0.baidu.com/it/u=2831381885,3119737412&fm=26&fmt=auto&gp=0.jpg"
        }
      ],
      thumb_url:"https://wx.scoringchina.com/gplanett/image/thurmb.png",
      activityid:20,
      name:"万人高球乐一夏",
      starttime:'2021/07/02',
      endtime:'2021/07/02',
      address:{
        address:"广东省广州市天河区龙熹路2号 天河区高星练习场 ，广州，天河区",
        latitude: 23.145089,
        longitude:113.377172,
        name:"广州高星娱乐中心",
      }
    }*/
  ],
    
    matchinprogress: true,
    matchinregsiter: undefined,
    userInfo: {},
    logged: false,
    takeSession: false,
    requestResult: '',
    matchinfo: undefined,
    matchinforeg: undefined,
    matchleaders: undefined,
    currentTabgroup: 0,
    yearranking: [],
    sponsorlogoes: [],
    indexpageimagespageno: 0,
    indexpageimagespagedata: [],
    timer:'',
    newspageno:1,
    picpageno:1,
    pastchampion:[],
    liveinfo:[],
    resliveinfo:[],
  },

   /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (options) {
    var that = this;
    // 设置菜单中的转发按钮触发转发事件时的转发内容
    var shareObj = {
      title:  app.langpagcke.apptitle[0]  + " " + app.langpagcke.apptitle[1] + '官方小程序' , // 默认是小程序的名称(可以写slogan等)
      path: '/pages/index/index', // 默认是当前页面，必须是以‘/’开头的完整路径
      imageUrl:'/images/thurmb.png',
      //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
      success: function (res) {
        // 转发成功之后的回调
        if (res.errMsg == 'shareAppMessage:ok') {
          console.log(res);
        }
      },
      fail: function () {
        // 转发失败之后的回调
        if (res.errMsg == 'shareAppMessage:fail cancel') {
          // 用户取消转发
        } else if (res.errMsg == 'shareAppMessage:fail') {
          // 转发失败，其中 detail message 为详细失败信息
        }
      },
      complete: function () {
        // 转发结束之后的回调（转发成不成功都会执行）
      }

    };
    // 来自页面内的按钮的转发
    if (options.from == 'button') {
      var eData = options.target.dataset;
      console.log(eData.id); // shareBtn
      // 此处可以修改 shareObj 中的内容
     
    }
    // 返回shareObj
    return shareObj;
  },

    /**
   * 用户分享朋友圈
   */
  onShareTimeline(){
    var that = this;
    // 设置菜单中的转发按钮触发转发事件时的转发内容
    var shareObj = {
      title:  app.langpagcke.apptitle[0]  + " " + app.langpagcke.apptitle[1] + '官方小程序' , // 默认是小程序的名称(可以写slogan等)
      query: 'userID='+ app.globalData.userInfo.userID , // 默认是当前页面，自定义页面路径中携带的参数，如 path?a=1&b=2 的 “?” 后面部分
      imageUrl:'/images/iconlogo.png',
      //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径，支持PNG及JPG，不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
     

    };
   
    // 返回shareObj
    return shareObj;
},


  onLoad: function () {
   
   this.gettitles();

 

    ///获取首页滚动照片
    this.getIndexpics();

    //获取组织架构
    this.getleaders();
    /*
    ///获取正在进行的比赛信息
    this.getmatchinprogress(false);
    ///获取正在报名的比赛
    this.getmatchinforeg();
   */


   //data
   this.getmatchesdata();
   this.getmatchesscoredata();

   ///获取首页视频
   this.getindexpagevideo();
   
   //获取首页的会员
   this.getmemebers();

    ///获取新闻类别
    this.getArtLists();

   // this.getindexactivity();

    //获取球队排名信息
    this.getteamranking();

    ///最近的冠军
    this.getpastchampion();

    ///获取积分排名
    this.getranking();

    ///获取首页的相册
    this.getindexpageimages();

    ///获取赞助商
    this.getSponsors();


    //获取我的赛事
    this.getmytour();

    // 获取用户信息
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              this.setData({
                avatarUrl: res.userInfo.avatarUrl,
                userInfo: res.userInfo
              })
            }
          })
        }
      }
    })
  },


  //data
  getmatchesdata:function(){
    var that = this;
    app.getmatchesdata("","",function(res){
      console.log("getmatchesdata-res",res);
      if(res.data.data){

        that.setData({tourdata:res.data.data});
      }
      else{
     
        that.setData({tourdata:""});
      }
 },function(){

 }) ;
  },

  getmatchesscoredata:function(){
    var that = this;
    app.getmatchesscoredata("","",function(res){
      console.log("getmatchesscoredata-res",res);
      if(res.data.data){
        var all_scores_max =  res.data.data.all_scores_max;
        all_scores_max.minbmt = getmatchshortname(  all_scores_max.minbmt);
        all_scores_max.mininsmt = getmatchshortname(  all_scores_max.mininsmt);
        all_scores_max.minmt = getmatchshortname(  all_scores_max.minmt);
        all_scores_max.minnetmt = getmatchshortname(  all_scores_max.minnetmt);
        all_scores_max.minouttmt = getmatchshortname(  all_scores_max.minouttmt);
        all_scores_max.diffmt = getmatchshortname(  all_scores_max.diffmt);
        
        that.setData({tourscoredata:all_scores_max});
      }
      else{
     
        that.setData({tourscoredata:""});
      }
 },function(){

 }) ;
 app.getmatchesplayeredata("","",function(res){
  console.log("getmatchesplayeredata-res",res);
  if(res.data.data){
    var all_players_max =  res.data.data.all_players_max;
    all_players_max.fmt = getmatchshortname(  all_players_max.fmt);
    all_players_max.mintmt = getmatchshortname(  all_players_max.mintmt);
    all_players_max.mmt = getmatchshortname(  all_players_max.mmt);
    all_players_max.pmt = getmatchshortname(  all_players_max.pmt);
    that.setData({tourplayersdata:res.data.data.all_players_max});
  }
  else{
 
    that.setData({tourplayersdata:""});
  }
},function(){

}) ;


 
  },


  getlivereserveInfo(){
    var that = this;
    var resliveinfo = [];
    wx.getChannelsLiveNoticeInfo({ finderUserName: app.globalData.channelsfeedID, // 视频号 ID 
    success(res) {  
      console.log('getlivereserveInfo',res);
      //res.noticeId // 预告 id res.status // 预告状态，0: 可用、1: 取消、2: 已用 res.startTime // 开始时间 res.headUrl // 直播封面 res.nickname // 视频号昵称 res.reservable // 是否可预约 //res.otherInfos 其他的预告信息列表（注意：每次最多返回按时间戳增序排列的15个预告信息，其中时间最近的那个预告信息会在接口其他的返回参数中展示，其余的预告信息会在该字段中展示）。
      if(res.noticeId){  //有预约的状态
        var date = new Date(res.startTime*1000);
        res.startTimestr =  date.getMonth()+1 + '月' + date.getDate()+'日 ' + date.getHours() + ':' + date.getMinutes() ;
        resliveinfo.push(res);
          if(res.otherInfos && res.otherInfos.length>0){
           
            res.otherInfos.forEach(v=>{
              var tdate = new Date(v.startTime*1000);
              v.startTimestr = tdate.getMonth()+1 + '月' + tdate.getDate()+'日 ' + tdate.getHours() + ':' + tdate.getMinutes() ;
        
              resliveinfo.push(v);
            })
          }
          that.setData({resliveinfo:resliveinfo});
      }
      else{
        that.setData({resliveinfo:resliveinfo});
      }
    },
    fail(res){
      that.setData({resliveinfo:resliveinfo});
    }
  }) 
  },

   getliveInfo(){
    var that = this;
    var liveinfo = [];
    wx.getChannelsLiveInfo({ finderUserName: app.globalData.channelsfeedID, // 视频号 ID 
    success(res) {  
      console.log('getliveInfo',res);
      //res.noticeId // 预告 id res.status // 预告状态，0: 可用、1: 取消、2: 已用 res.startTime // 开始时间 res.headUrl // 直播封面 res.nickname // 视频号昵称 res.reservable // 是否可预约 //res.otherInfos 其他的预告信息列表（注意：每次最多返回按时间戳增序排列的15个预告信息，其中时间最近的那个预告信息会在接口其他的返回参数中展示，其余的预告信息会在该字段中展示）。
      if(res.feedId && res.nonceId && res.status == 2 ){  //有预约的状态
       
        liveinfo.push(res);
        
        if(res.otherInfos && res.otherInfos.length>0){
           
          res.otherInfos.forEach(v=>{
           
            liveinfo.push(v);
          })
        }
          that.setData({liveinfo:liveinfo});
      }
      else{
        that.setData({liveinfo:liveinfo});
      }
    },
    fail(res){
      that.setData({liveinfo:liveinfo});
    }
  }) 
  },


  openlive:function(e){
    var liveinfo = e.currentTarget.dataset.liveinfo;
    wx.openChannelsLive({
        finderUserName:app.globalData.channelsfeedID,
       noticeId: liveinfo.noticeId, // 上面获取到的直播预告 id
       feedId:liveinfo.feedId,
       success(res){
         
       }
     });
  },


  reverslive(e){
    var resliveinfo = e.currentTarget.dataset.resliveinfo;
    wx.reserveChannelsLive({ noticeId: resliveinfo.noticeId, // 上面获取到的直播预告 id
     });
     this.getliveInfo();
  },

  gettitles(){
      var year = new Date().getFullYear();
      var startyear = 2022 ;
      
      var content = '第' +  convertToChinaNum(year-startyear +1 ) + '届';
      this.setData({titlecontent:content +this.data.titlecontent});
  },

  onReady: function () {
   
  },

onHide:function(){
  console.log('onHide');
  if(this.data.timer){
    console.log(this.data.timer);
    clearInterval(this.data.timer);
  }
},

  onGetUserInfo: function (e) {
    if (!this.data.logged && e.detail.userInfo) {
      this.setData({
        logged: true,
        avatarUrl: e.detail.userInfo.avatarUrl,
        userInfo: e.detail.userInfo
      })
    }
  },


  //获取组织架构  
  getleaders(){
    var that = this;
    app.getleaders(function(res){
      console.log("getleaders-res",res);
      if(res.data.data.leaders){

        that.setData({leaders:res.data.data.leaders});
      }
      else{
     
        that.setData({leaders:[]});
      }
 },function(){

 }) ;
  },

  ///获取首页相册
  getindexpageimages: function () {
    var that = this;
     app.getmedia("index", 0, "pic", function(res){
          console.log("getindexpageimages-res");
          console.log(res);
          if(res.data.data.news){
         
              that.setData({indexpageimagespagedata:res.data.data.news});
              console.log("that.data.indexpageimagespagedata");
              console.log(that.data.indexpageimagespagedata);
          }
          else{
            console.log("that.data.thurmbs:[]");
            that.setData({indexpageimagespagedata:[]});
          }
     }, that.data.picoffset, that.data.picpageno,function(){

     }) ;
   
    
  },
  _openteaminfo:function(e){
      var {tm_name} = e.currentTarget.dataset;
      wx.navigateTo({
        url: '../teaminfo/teaminfo?tmname='+tm_name,
      })
  },

 

  _openranking:function(){
    wx.switchTab({
    
      url: '../Ranking/index',
    })
  },

  _openintro:function(){
      wx.navigateTo({
        url: '../introduce/index',
      })
  },

  _openmember:function(e){
    const {member} = e.currentTarget.dataset;
    if(member){
      wx.navigateTo({
        url: '../Players/playerinfo/index?selectid='+member.playerID,
      })
    }
  },

  _openmembers:function(){
      wx.navigateTo({
        url: '../Players/index',
      })
  },

  changemember:function(e){
    console.log(e);
  },

  //获取首页的会员信息
  getmemebers:function(){
      var that = this;   //getmemebers: function (index, matchid, sex_id,pageno, type, fnSuccse, keywords, fnfinal) {
        this.setData({isloadingmember:true});
     app.getmemebers("index", 0,"",0, "index", function(res){
          console.log("getmemebers-res");
          console.log(res);
          if(res.data.data && res.data.data.players){
              that.setData({members:res.data.data.players,memberpageno:res.data.data.pageno,totalmembercount:res.data.data.totalcount});
              console.log("that.data.indexpageimagespagedata");
              console.log(that.data.members);
          }
          else{
            console.log("that.data.thurmbs:[]");
            that.setData({members:[]});
          }
     },"",function(){
       console.log("isloadingmember",that.data.isloadingmember);
       that.setData({isloadingmember:false});
     }) ;
   
  },

  ///获取首页视频打开视频号
  getindexpagevideo: function () {
    var that = this;
     app.getmedia("", 0, "media", function(res){
          console.log("getindexpagevideo-res");
          console.log(res);
          if(res.data.data.news){
         
              that.setData({channels_items:res.data.data.news});
              console.log("that.data.indexpageimagespagedata");
              console.log(that.data.indexpageimagespagedata);
          }
          else{
            console.log("that.data.thurmbs:[]");
            that.setData({channels_items:[]});
          }
     }, that.data.picoffset, that.data.picpageno,function(){

     }) ;
   
    
  },


  getindexactivity:function(){
  
    var that = this;
    app.getactivitylists(1,function(res){
      if(res.data.data){
        console.log("getindexactivity");
        console.log(res.data.data);
        that.setData({events_items:res.data.data});
       
      }
    
    },function(){});
  },

  ///获取所有的赞助商列表
  getSponsors: function () {
    var that = this;
    app.getlogoes(function(res){
      if(res.data.data){
     
        console.log("sponsorlogoes",res.data.data);
        that.setData({sponsorlogoes:res.data.data.loges});
        app.globalData.sponsorlogoes = that.data.sponsorlogoes;

        if(res.data.data.ads ){
          app.globalData.bannerAd = res.data.data.ads;
          wx.setStorageSync('AD',  app.globalData.bannerAd);
        }
        else{
          app.globalData.bannerAd ="";
          wx.setStorageSync('AD',  app.globalData.bannerAd);
        }
      }
    
    },0);
   
  },

  ///获取新闻类别
  getArtLists() {
    var that = this;
    app.getmedia(0, 0, "news", function (res) {
      console.log("indexmedia");
      console.log(res.data.data.news);
      that.setData({ news_items: res.data.data.news });
    });
  },

  ///获取首页图片
  getIndexpics() {
    var that = this;
   
    
    app.getIndexpics(
      function(res){
          if(res.data.data.news){
            var indexpageUrl= [];
            var thurmbs = res.data.data.news;
            for(var index= 0;index<thurmbs.length;index++)
            {
              indexpageUrl.push(thurmbs[index]);
            }
              that.setData({indexpageUrl:indexpageUrl});
              console.log("that.data.indexpageUrl");
              console.log(that.data.indexpageUrl);
          }
          else{
            console.log("that.data.indexpageUrl:[]");
            that.setData({indexpageUrl:[]});
          }
      })
    

  },

  //打开球员成绩页面
  _openpastchampion(e){
    let playerorteam = 0; //是否是team团队成绩卡
    let isteam =  e.currentTarget.dataset.isteam;
    console.log(isteam);
    if(isteam){
      let selectid = e.currentTarget.dataset.leaders.id;
      let matchinfo = e.currentTarget.dataset.matchinfo;
      let matchid = matchinfo.matchid;
      let teamname = e.currentTarget.dataset.leaders.name;
      console.log(e.currentTarget.dataset.leaders);
      wx.navigateTo({
        url: '../Scorecard/team/index?selectid=' + selectid + "&matchid=" + matchid +
          "&teamname=" + teamname + "&matchinfo=" + encodeURIComponent(JSON.stringify(matchinfo)),
      })
    }
    else{
      let selectid = e.currentTarget.dataset.leaders.playerID;
      let matchinfo = e.currentTarget.dataset.matchinfo;
      let playername = e.currentTarget.dataset.leaders.playername;
      console.log(e.currentTarget.dataset.leaders);
      wx.navigateTo({
        url: '../Scorecard/player/index?selectid=' + selectid + "&playerorteam=" + playerorteam +
          "&playername=" + playername + "&matchinfo=" + encodeURIComponent(JSON.stringify(matchinfo)),
      })
   }
  },

//打开微信的视频号
_openchannel(e) {


  let channel_itemobj = e.currentTarget.dataset.channel;; //JSON.parse(newsitem.replace(" ", "").replace(/\ufeff/g, ""));
  console.log("channel_itemobj");
  console.log(channel_itemobj);
  if(channel_itemobj){
    wx.openChannelsActivity({
    
      finderUserName:channel_itemobj.pl_name,
      feedId:channel_itemobj.digest,
      success:function(errMsg){
        console.log(errMsg);
      },
      fail:function(errMsg){
        console.log(errMsg);
      },
      complete:function(){
        console.log();
      }
    })
    
  }
},

  //打开微信的新闻页面
  _opennews(e) {


    let news_itemobj = e.detail.newsitem;; //JSON.parse(newsitem.replace(" ", "").replace(/\ufeff/g, ""));
    console.log("_opennews");
    console.log(news_itemobj);
    if (news_itemobj.url != undefined) {
      this.setData({
        news_url: news_itemobj.url
      });
      console.log('../URL/index?weburl=' + encodeURIComponent(news_itemobj.url));
      app.globalData.selectnewcontentobj = news_itemobj;
    wx.navigateTo({
        url: '../URL/index?weburl='+encodeURIComponent(news_itemobj.url)+"&type=新闻&title="+ news_itemobj.title
      })
     // wx.navigateTo({
      //  url: '../URL/newpage/index?weburl=' + encodeURIComponent(news_itemobj.url) + "&title=" + news_itemobj.title + "&type='" + '新闻页面'
     // })

    } else {

    }
  },

  //打开微信的新闻页面
  _opennewsindex(e) {


    let news_itemobj = e.currentTarget.dataset.newsitem;; //JSON.parse(newsitem.replace(" ", "").replace(/\ufeff/g, ""));
    console.log("_opennews");
    console.log(news_itemobj);
    if (news_itemobj.url) {
      this.setData({
        news_url: news_itemobj.url
      });
      console.log('../URL/index?weburl=' + encodeURIComponent(news_itemobj.url));
      app.globalData.selectnewcontentobj = news_itemobj;
    wx.navigateTo({
        url: '../URL/index?weburl='+encodeURIComponent(news_itemobj.url)+"&type=新闻&title="+ news_itemobj.title
      })
     // wx.navigateTo({
      //  url: '../URL/newpage/index?weburl=' + encodeURIComponent(news_itemobj.url) + "&title=" + news_itemobj.title + "&type='" + '新闻页面'
     // })

    } else {

    }
  },
   


  _openevent:function(e){
    let events_item = e.detail.events_item; //JSON.parse(newsitem.replace(" ", "").replace(/\ufeff/g, ""));
    console.log("events_item");
    console.log(events_item);
    if (events_item.activityid) {
     
    wx.navigateTo({
        url: '../activity/activity?activityid='+ events_item.activityid
      })
  

    }
  },

  //打开playerscorecard 页面 
  _openplayerCard(e) {
    console.log(e);
    let playerorteam = e.detail.playerorteam; //是否是team团队成绩卡
    let selectid = e.detail.selectid;
    let matchinfo = JSON.parse(e.detail.matchinfo);
    let playername = e.detail.playername;
    wx.navigateTo({
      url: '../Scorecard/player/index?selectid=' + selectid + "&playerorteam=" + playerorteam +
        "&playername=" + playername + "&matchid=" + matchinfo.matchid,
    })
    // 将参数的形式传递给父组件
  },


  
     //打开playerscorecard 页面 
     _openmatchbyscores(e) {
      let matchid = e.currentTarget.dataset.matchid;
      console.log(matchid);
        wx.navigateTo({
          url: '../Tournament/match?matchid='+matchid
        })
      // 将参数的形式传递给父组件
    },
   //打开playerscorecard 页面 
   _openplayerCardbyscores(e) {
    console.log(e);
    let playerorteam = 0; //是否是team团队成绩卡
    let selectid = e.currentTarget.dataset.player_id;
    let matchid = e.currentTarget.dataset.matchid;
    let playername = e.currentTarget.dataset.playername;
    wx.navigateTo({
      url: '../Scorecard/player/index?selectid=' + selectid + "&playerorteam=" + playerorteam +
        "&playername=" + playername + "&matchid=" + matchid,
    })
    // 将参数的形式传递给父组件
  },
  
//打开playerscorecard 页面 
_openteamCard(e) {
  console.log(e);
  let selectid = e.detail.selectid;
  let matchinfo = JSON.parse(e.detail.matchinfo);
  let teamname = e.detail.teamname;
  wx.navigateTo({
    url: '../Scorecard/team/index?selectid=' + selectid +
      "&teamname=" + teamname + "&matchid=" + matchinfo.matchid,
  })
  // 将参数的形式传递给父组件
},
  

  ///打开注册页面
  _openmatchreg(e) {
    let matchinfo = e.detail.matchinfo;
    app.globalData.selectmatchinfo = matchinfo;
    wx.navigateTo({
      url: '../Tournament/match'
    })

  },

  ///打开直播页面
  _openlive(e){
    let matchinfo = e.detail.matchinfo;
    app.globalData.selectmatchinfo = matchinfo;
    wx.navigateTo({
      url: '../Tournament/live/index'
    })
  },

  //打开地图位置
  getLocation: function (e) {

    e = this.data.matchinfo.courseinfo.courseadress;
   /* wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        wx.openLocation({ //​使用微信内置地图查看位置。
          latitude: Number(e.latitude), //要去的纬度-地址
          longitude: Number(e.longitude), //要去的经度-地址
          name: e.name,
          address: e.address
        })
      }
    })*/
  },

  //获取正在开始比赛的成绩
  getmatchinprogressleaders(matchinfolist, isautorefresh) {
    var that = this;
    var matchleaders  = [];
    
    var currentMatchlists = matchinfolist;
    console.log("getmatchinprogressleaders");
    console.log(currentMatchlists);
    if(!currentMatchlists){
      return;
    }
    
    for(var index = 0; index<currentMatchlists.length;index++ ){
      app.getmatchleadersbyround(currentMatchlists[index].matchid,currentMatchlists[index].currentround, function (res) {
        matchleaders.push(res.data.data);  
        console.log("matchleaders");    
        console.log(matchleaders);        
        that.setData({matchleaders:  matchleaders  });
       // app.globalData.currentMatch = that.data.match;    
      });
    }

   
    

  },

  //获取正在报名的比赛
  getmatchinforeg(isautorefresh) {
    var that = this;
    app.getmatchinforeg(new Date().getFullYear(),"",function (res) {
     console.log("getmatchinforeg");
     console.log(res.data.data.monthmatches);
      if(res.data.data.monthmatches){
        var monthmathes = res.data.data.monthmatches;
        var matchinfo = [];
        for(var index=0;index<monthmathes.length;index++){
            var matches = monthmathes[index].matches;
            for(var matchindex=0;matchindex<matches.length;matchindex++){
            if(matches[matchindex].matchstatuscode=='R'){
              console.log("matches[matchindex]");
              console.log(matches[matchindex]);
              matchinfo.push(matches[matchindex]);
            }
          }
        }
        that.setData({
          matchinforeg: matchinfo
        })
      console.log("getmatchinfo-matchinfo");
      console.log(that.data.matchinforeg);
      }
      else{
        that.setData({
          matchinfo: null
        })
      }
    
  },function () {
    if (!isautorefresh) {
     
      wx.hideLoading();
    }
  });
   
  },
 

  //获取赛事信息
  getmatchinprogress(isautorefresh) {
    
    var that = this;
    if (!isautorefresh) {
     
    wx.showNavigationBarLoading();
  }
  app.getmatchinprogress(new Date().getFullYear(),"",function (res) {
      console.log("getmatchinprogress-res");
      console.log(res);
      if(res.data.data.monthmatches){

        var monthmathes = res.data.data.monthmatches;
        var matchinfo = [];
        for(var index=0;index<monthmathes.length;index++){
            var matches = monthmathes[index].matches;
            if(matches){
              matchinfo = matchinfo.concat(matches);
            }
        }
        that.setData({
          matchinfo: matchinfo
        })
      console.log("getmatchinforeg-matchinfo");
      console.log(that.data.matchinfo);

      ///获取正在进行比赛的成绩
      that.getmatchinprogressleaders(that.data.matchinfo, isautorefresh);
      if(that.data.timer!= ''){
        clearInterval(that.data.timer);
      }
      else
      var timer = setInterval(function() {
        console.log("matchinfo");
        console.log(matchinfo);
        that.getmatchinprogressleaders(matchinfo,true);
        console.log("index:刷新30秒了----------------------------------------------------")
      }, app.globalData.refreshtime);
      that.setData({timer:timer});
    
    }
    else{ 

      that.setData({
        matchinfo: null,
        matchleaders:null
      })
       
    }
    
  },function () {
    if (!isautorefresh) {
     
      wx.hideNavigationBarLoading();
    }
  });
   
    
      


   
  },

  ///获取最近冠军
  getpastchampion() {
  

    var that = this;
    var year =  new Date().getFullYear() ;
    var that = this;
    wx.showLoading({
      title: '加载中',
    })
    app.getpastchampion(year,
      function(res){
          if(res.data.data){
            console.log("getpastchampion");
            console.log(res.data.data);
            that.setData({
              pastchampion:res.data.data
             })
             
            }
      },function(){
        wx.hideLoading()
      })
  },
///获取排名
getteamranking() {
  

  var that = this;
  var year =  new Date().getFullYear()  , offset  = 5;
  var that = this;
  wx.showNavigationBarLoading({
    success: (res) => {},
  })
  app.getteamranking(year,
    function(res){
      console.log("getteamranking",res);
        if(res.data.data){
          that.setData({
            yearteamranking:res.data.data.rankingleaders
           })
          
          }
    },function(){
      wx.hideNavigationBarLoading({
        success: (res) => {},
      })
    })
},

bindDateChange:function(e){
  console.log(e);
   this.setData({
     selectarea:this.data.yearranking.areas[e.detail.value],
  });
   this.getranking();
},


  //获取积分排名前5
  ///获取排名
  getranking() {
  

    var that = this;
    var year =  new Date().getFullYear()  , offset  = 5;
    var that = this;
    wx.showNavigationBarLoading({
      success: (res) => {},
    })
    app.getranking(year,offset,this.data.selectarea,"",
      function(res){
        console.log("getranking",res);
          if(res.data.data){
            that.setData({
              yearranking:res.data.data
             })
            
            }
      },function(){
        wx.hideNavigationBarLoading({
          success: (res) => {},
        })
      })
  },

 //获取我的比赛
  getmytour:function(){
      var userInfo =  app.globalData.userInfo?app.globalData.userInfo: wx.getStorageSync('userInfo');
      var that = this;
      if(!app.globalData.userInfo){
        app.globalData.userInfo = userInfo;
       }
      if(userInfo.player_id){
        app.getmytour('',
          function(res){
            console.log("getmytour",res);
              if(res.data.data){
                that.setData({
                  mytour:res.data.data
                 })
               
                }
          },function(){
            wx.hideNavigationBarLoading({
              success: (res) => {},
            })
          })
      }
  },

  //积分排名切换组别
  swichNav: function (e) {
    var that = this;
    if (that.data.currentTabgroup === e.target.dataset.current) {

      return false;
    } else {
      that.setData({
        currentTabgroup: e.target.dataset.current
      })


    }

  },

  onGetOpenid: function () {
    // 调用云函数
    wx.cloud.callFunction({
      name: 'login',
      data: {},
      success: res => {
        console.log('[云函数] [login] user openid: ', res.result.openid)
        app.globalData.openid = res.result.openid
        wx.navigateTo({
          url: '../userConsole/userConsole',
        })
      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
        wx.navigateTo({
          url: '../deployFunctions/deployFunctions',
        })
      }
    })
  },

  // 上传图片
  doUpload: function () {
    // 选择图片
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {

        wx.showLoading({
          title: '上传中',
        })

        const filePath = res.tempFilePaths[0]

        // 上传图片
        const cloudPath = 'my-image' + filePath.match(/\.[^.]+?$/)[0]
        wx.cloud.uploadFile({
          cloudPath,
          filePath,
          success: res => {
            console.log('[上传文件] 成功：', res)

            app.globalData.fileID = res.fileID
            app.globalData.cloudPath = cloudPath
            app.globalData.imagePath = filePath

            wx.navigateTo({
              url: '../storageConsole/storageConsole'
            })
          },
          fail: e => {
            console.error('[上传文件] 失败：', e)
            wx.showToast({
              icon: 'none',
              title: '上传失败',
            })
          },
          complete: () => {
            wx.hideLoading()
          }
        })

      },
      fail: e => {
        console.error(e)
      }
    })
  },

  // 下拉刷新方法
  onPullDownRefresh: function () {
    // 显示标题栏进度条效果
    wx.showNavigationBarLoading();

    ///获取正在进行的比赛信息
    this.getmatchinprogress();

    ///获取即将进行的比赛
    this.getmatchinprepare();

       //获取首页的会员
   this.getmemebers();
   
    //获取球队排名信息
    this.getteamranking();

    this.getranking();

    ///获取正在进行比赛的成绩
    this.getmatchinprogressleaders(this.data.matchinfo);

    ///获取正在报名的比赛
    this.getmatchinforeg();

      ///获取首页视频
   this.getindexpagevideo();

    ///获取新闻类别
    this.getArtLists();

    
    //获取我的赛事
    this.getmytour();

    //
    //this.getindexactivity();

  

    ///最近的冠军
    this.getpastchampion();

    // 取消标题栏进度条效果
    wx.hideNavigationBarLoading();
    // 取消页面刷新动画
    wx.stopPullDownRefresh();

  },

  // 上拉加载方法
  onReachBottom: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0
      })
    }
      ///获取正在进行的比赛信息
      this.getmatchinprogress();

      
         ///获取即将进行的比赛
         this.getmatchinprepare();

         //data
         this.getmatchesdata();
         this.getmatchesscoredata();
          //获取直播信息
          this.getliveInfo();
          //获取直播预约信息
          this.getlivereserveInfo();

      ///获取正在进行比赛的成绩
      this.getmatchinprogressleaders(this.data.matchinfo);
  
      ///获取正在报名的比赛
      this.getmatchinforeg();

      
    //获取我的赛事
    this.getmytour();
  },

  onResize: function (res) {
    this.onShow();
  },

  getliveinfo:function(){
   /* wx.getChannelsLiveNoticeInfo({
      finderUserName:'sphY9HOTLiCELsX',
      success:function(res){
          console.log("getliveinfo",res);
      },
      fail:function(res){
        console.log("getliveinfo-fail",res);
      }
    })*/
  },

  ///打开matchcard
  _openmatch: function (e) {
    /*wx.requestSubscribeMessage({
      tmplIds: ['LFT3BEcr7jfe4AtrHealLmgBsYujzpfPNIcC9c1GYR4'],
      success (res) { },
      fail(res){console.log(res)}
    });*/
    console.log(e);
  
    let matchinfo = e.currentTarget.dataset.matchinfo;
    let currenttab = e.currentTarget.dataset.currenttab;

    app.globalData.selectmatchinfo = matchinfo;
    wx.navigateTo({
      url: '../Tournament/match?currenttab='+currenttab
    })
  },

  //打开球员信息页面
  _openplayerinfo: function (e) {
    let selectid = "";
    if(e.currentTarget.dataset.selectid){
      selectid = e.currentTarget.dataset.selectid;
    }
    else{
    selectid = e.detail.selectid;
    }
    wx.navigateTo({
      url: '../Players/playerinfo/index?selectid=' + selectid,
    })

  },
  //搜索的方法
  _search: function (e) {
    let searchcontent = e.detail.searchcontent;
    wx.showToast({
      title: searchcontent,
      icon: 'none'
    })
  },

  
    //获取即将进行的赛事
    getmatchinprepare(isautorefresh) {
    
      var that = this;
      if (!isautorefresh) {
      wx.showNavigationBarLoading();
    }
    app.getmatchinprepare(new Date().getFullYear(),"",function (res) {
        console.log("getmatchinprepare-res");
        console.log(res);
        if(res.data.data.monthmatches){
  
          var monthmathes = res.data.data.monthmatches;
          var matchinpreparelists = [];
        for(var index=0;index<monthmathes.length;index++){
          var matches = monthmathes[index].matches;
          if(matches){
            matchinpreparelists = matchinpreparelists.concat(matches);
          }
        }

        var matchinprepare=[];
        for(var index = 0;index<matchinpreparelists.length;index++){
        
          var matchinfo = matchinpreparelists[index];
          var matchinprepareitem = {matchinfo:matchinfo,drawsheet:"",matchfiledlist:""};
        
          console.log(matchinfo);
          
          app.getmatchdrawsheet( matchinfo.matchid, 1, function (res) {
            console.log("getmatchdrawsheet-res");
            console.log(res);
            if (res.data.data.drawsheet && res.data.data.drawsheet.length>0) {
              console.log( matchinprepareitem);
              matchinprepareitem.drawsheet=res.data.data.drawsheet
              console.log( matchinprepareitem);
              matchinprepare.push(matchinprepareitem);
              that.setData({
              matchinprepare: matchinprepare
             })
            } else {
              matchinprepareitem.drawsheet="";
              app.getplayers("", matchinfo.matchid, "0", "all", function (res) {
                console.log('filedelist-res');
                console.log(res);
                console.log(matchinprepareitem);
                matchinprepareitem.matchfiledlist = res.data.data.players
                matchinprepare.push(matchinprepareitem);
                that.setData({
                  matchinprepare: matchinprepare
                })
              }, function () {
              });
            }
          
          }, function () {     
          });

         
         
         
        }
        
        console.log("matchinprepare");
        console.log(that.data.matchinprepare.length);
            if(that.data.preparetimer!= ''){
              clearInterval(that.data.preparetimer);
            }
            else
            var preparetimer = setInterval(function() {
              that.getmatchinprepare();
              console.log("index:刷新"+app.globalData.refreshtime * 2 * 5 +"秒了----------------------------------------------------")
            }, app.globalData.refreshtime * 2 * 5 );
            that.setData({preparetimer:preparetimer});
      
      }
      else{ 
        that.setData({
          matchinprepare:"",
        })
        if(that.data.preparetimer!= ''){
          clearInterval(that.data.preparetimer);
        }
      }
      
    },function () {
      if (!isautorefresh) {
       
        wx.hideNavigationBarLoading();
      }
    });
    },

    
  onPageScroll (e) { 
    //console.log(e);
     var that= this;
      wx.createSelectorQuery().select('#tourbanner').boundingClientRect(function(rect){
        
          if(rect){
              if(rect.top + rect.height <=0)     // 节点的上边界坐标{
              {
                that.setData({istop:true});
              }
              else{
                that.setData({istop:false});
              }
          }
        
    }).exec();
    },
})